﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using TomNet.AspNetCore.Identity;
using TomNet.AspNetCore.Mvc;
using TomNet.Core.Options;
using TomNet.Data;
using TomNet.Demo.Service.User;
using TomNet.Demo.Service.User.Input;
using TomNet.Entity;
using TomNet.Extensions;

namespace TomNet.Demo.Web.Controllers
{
    [Route("[controller]")]
    public class IdentityController : ApiControllerBase
    {
        private readonly IUserService _service;
        private readonly IServiceProvider _provider;

        public IdentityController(IUserService service, IServiceProvider provider)
        {
            _service = service;
            _provider = provider;
        }
        [HttpPost("token")]
        public async Task<IActionResult> GetTokenAsync([FromBody] LoginInput dto)
        {
            var result = new OpResult<object>();
            var res = await _service.Login(dto);
            if (res.Success)
            {
                var claims = new Claim[]
                {
                    new Claim(ClaimTypes.Name,res.Data.LoginName),
                    new Claim(ClaimTypes.NameIdentifier, res.Data.Id.ToString()),
                    new Claim(ClaimTypes.Role, "admin")
                };
                TomNetOptions options = HttpContext.RequestServices.GetTomNetOptions();
                var token = JwtHelper.CreateToken(claims, options);

                return Ok(result.OK(data: new { token = token.Item1, expires = token.Item2 }));

            }
            else
            {
                return Ok(res);
            }
        }

        [Authorize]
        [HttpGet("test")]
        public IActionResult Test()
        {
            var result = new OpResult<object>();
            var user = _provider.GetCurrentUser()?.Identity;
            var id = user.GetClaimValueFirstOrDefault(ClaimTypes.NameIdentifier);
            var name = user.GetClaimValueFirstOrDefault(ClaimTypes.Name);
            var role = user.GetClaimValueFirstOrDefault(ClaimTypes.Role);
            return Ok(result.OK(msg: "允许访问", data: new { Id = id, Name = name, Role = role }));
        }
    }
}
